package com.android.avy;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

enum STATE {CO, UT};

public class Avy extends ListActivity {
	
	static public final String COLORADO = "'CO'";
	static public final String UTAH = "'UT'";
	
	static public final String AVY_PREFS = "avy.prefs";
	
	static public final String[] TEST_PROJ = {ZoneData.ZoneDays._ID,
		ZoneData.ZoneDays.COL_NAME_ZONE,
		ZoneData.ZoneDays.COL_NAME_ROSE};
	static public final String[] TEST_VIEW_DATA_COLS = {ZoneData.ZoneDays.COL_NAME_ZONE,
		ZoneData.ZoneDays.COL_NAME_ROSE};
	static public final int[] TEST_VIEWS = {R.id.zone_name, R.id.zone_color};
    static public final String TEST_SELECT = ZoneData.ZoneDays.COL_NAME_STATE + "=" + COLORADO;

	
	private Cursor mCursor;
	private String loadedDay;
	static private Time mTime = new Time();
		
	static private final int AVY_WAIT_DIALOG = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // this causes onResume to call the AvyLoader
        loadedDay = "0";
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	    	
    	mTime.setToNow();
        if (!loadedDay.equalsIgnoreCase(mTime.format("%Y%m%d"))) {
    		//loadedDay = mTime.format("%Y%m%d");
        	loadedDay = "2011-03-02";
        	showDialog(AVY_WAIT_DIALOG);
    		new AvyLoader().execute(loadedDay);
    	}
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog;
    	switch (id) {
    	case AVY_WAIT_DIALOG:
    		dialog = new MyDialog(this);
    		break;
    	default:
    		dialog = null;
    	}
    	return dialog;
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	Cursor c = (Cursor) getListView().getItemAtPosition(position);
    	String myId = c.getString(c.getColumnIndex("_id"));
    	
    	Intent intent = new Intent();
    	intent.setAction(Intent.ACTION_VIEW);
    	intent.setType(ZoneData.ZoneDays.CONTENT_TYPE_ITEM);
    	intent.setData(Uri.parse(ZoneData.ZoneDays.CONTENT_URI_BASE + myId));
    	
    	startActivity(intent);
    }
    
    
    private class MyDialog extends Dialog {

		public MyDialog(Context context) {
			super(context);
			
			this.setContentView(R.layout.avy_wait_dialog);
			ImageView iv = (ImageView) this.findViewById(R.id.wait_rose_view);
			iv.setImageDrawable(DangerRose.getWaitRose());
		}
		
		@Override
		public void onWindowFocusChanged(boolean hasFocus) {
			// TODO Auto-generated method stub
			super.onWindowFocusChanged(hasFocus);
			
			ImageView iv = (ImageView) this.findViewById(R.id.wait_rose_view);
			AnimationDrawable ad = (AnimationDrawable) iv.getDrawable();
			if (hasFocus) {
				ad.start();
			} else {
				ad.stop();
			}
		}
		
		
    	
    }
    
    private class MyAdapter extends ArrayAdapter<String> {
    	public MyAdapter() {
    		super(Avy.this,
    				R.layout.home_list_item,
    				R.id.zone_name,
    				Avy.this.getResources().getStringArray(R.array.zone_names_co));
		}
    	
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		
    		LinearLayout ll;
    		if (convertView == null) {
    			LayoutInflater li = (LayoutInflater) Avy.this.getSystemService(LAYOUT_INFLATER_SERVICE);
    			ll = (LinearLayout) li.inflate(R.layout.home_list_item, null);
    		} else {
    			ll = (LinearLayout) convertView;
    		}
    		
    		ImageView iv = (ImageView) ll.findViewById(R.id.zone_color);
    		//iv.setBackgroundDrawable(DangerRose.getWaitRose());
    		iv.setImageDrawable(DangerRose.getNewWaitRose());

    		TextView tv = (TextView) ll.findViewById(R.id.zone_name);
    		tv.setText(getItem(position));
    		
    		return ll;
    	}
    }
    
    private class AvyViewBinder implements ViewBinder {

    	/** 
    	 * Get the data from the cursor and use it to set the view
    	 */
		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {	
			
			String colName = cursor.getColumnName(columnIndex);
			if (colName.equalsIgnoreCase(ZoneData.ZoneDays.COL_NAME_ROSE)) {
				// build the danger rose
				ImageView iv = (ImageView) view;
				iv.setImageDrawable(DangerRose.buildRose(cursor.getString(columnIndex)));
				return true;
			} else if (colName.equalsIgnoreCase(ZoneData.ZoneDays.COL_NAME_ZONE)) {
				TextView tv = (TextView) view;
				tv.setText(cursor.getString(columnIndex));
				return true;
			} else {
				return false;
			}
			
		}
    	
    }
    
    
    private class AvyLoader extends AsyncTask<String, Void, Void> {
    	
    	public AvyLoader() {
    		super();
    	}
    	
		@Override
		protected Void doInBackground(String... days) {
			
			/*
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			*/
			
			AvyUpdater au = new AvyUpdater(getContentResolver());
			au.refreshDay(days[0]);
			
			// add only this day to the selection
			String selection = TEST_SELECT + " AND " + 
				ZoneData.ZoneDays.COL_NAME_DATE + "='" + days[0] + "'";
			mCursor = managedQuery(ZoneData.ZoneDays.CONTENT_URI, TEST_PROJ, selection, null, null);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void v) {
	        //Avy.this.mDialog.dismiss();
			Avy.this.dismissDialog(AVY_WAIT_DIALOG);
			
	        if (mCursor.getCount() == 0) {
	        	Toast.makeText(Avy.this, "Update failed", Toast.LENGTH_SHORT).show();
	        } else {
	        	SimpleCursorAdapter avyListAdapter = new SimpleCursorAdapter(Avy.this, R.layout.home_list_item, mCursor, TEST_VIEW_DATA_COLS, TEST_VIEWS);
		        avyListAdapter.setViewBinder(new AvyViewBinder());
		        
	        	setListAdapter(avyListAdapter);
	        	
	        	DangerRose.getWaitRose().stop();
	        }
		}
    	
    }
    
}